import React, { useMemo } from 'react';

declare module 'react' {
  interface CSSProperties {
    '--grid-cols'?: string;
    '--grid-gap'?: string;
  }
}
import '../css/heatmap.css';

// 颜色工具类
class ColorUtils {
    static hexToRgb(hex: string) {
        const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
        return result ? {
            r: parseInt(result[1], 16),
            g: parseInt(result[2], 16),
            b: parseInt(result[3], 16)
        } : null;
    }
    
    static getColorInGradient(lowColor: {r: number, g: number, b: number}, highColor: {r: number, g: number, b: number}, ratio: number) {
        const r = Math.round(lowColor.r + (highColor.r - lowColor.r) * ratio);
        const g = Math.round(lowColor.g + (highColor.g - lowColor.g) * ratio);
        const b = Math.round(lowColor.b + (highColor.b - lowColor.b) * ratio);
        
        return `rgb(${r},${g},${b})`;
    }
}

// 热力图配置接口
export interface HeatmapConfig {
    rows: number;
    cols: number;
    rounded?: number;
    roundedUnit?: string;
    gap?: number;
    gapUnit?: string;
    maxValue?: number;
    data?: number[][];
    lowColor?: string;
    highColor?: string;
}

// 热力图组件接口
export interface HeatmapProps {
    id: string;
    config: HeatmapConfig;
    onCellClick?: (rowIndex: number, colIndex: number, value: number) => void;
}

const Heatmap: React.FC<HeatmapProps> = ({ id, config, onCellClick }) => {


    // 生成热力图默认数据
    const generateDefaultHeatmapData = (rows: number, cols: number, maxValue: number): number[][] => {
        const data: number[][] = [];
        for (let i = 0; i < rows; i++) {
            data[i] = [];
            for (let j = 0; j < cols; j++) {
                data[i][j] = Math.floor(Math.random() * maxValue);
            }
        }
        return data;
    };

    // 处理配置默认值
    const heatmapConfig = useMemo(() => {
    const data = config.data || generateDefaultHeatmapData(config.rows || 10, config.cols || 10, config.maxValue || 100);
    const maxValue = config.maxValue !== undefined ? config.maxValue : Math.max(...data.flat(), 1);
    return {
        rows: config.rows || 10,
        cols: config.cols || 10,
        rounded: config.rounded || 4,
        roundedUnit: config.roundedUnit || 'px',
        gap: config.gap || 1,
        gapUnit: config.gapUnit || 'px',
        maxValue,
        data,
        lowColor: config.lowColor || '#f3f4f6',
        highColor: config.highColor || '#ef4444'
    };
}, [config]);

    // 计算单元格颜色
    const getCellColor = (value: number) => {
        const normalizedValue = Math.min(value / heatmapConfig.maxValue, 1);
        const lowColorRgb = ColorUtils.hexToRgb(heatmapConfig.lowColor) || {r: 243, g: 244, b: 246};
        const highColorRgb = ColorUtils.hexToRgb(heatmapConfig.highColor) || {r: 239, g: 68, b: 68};
        
        const gradientSteps = 5;
        const step = 100 / gradientSteps;
        const stepIndex = Math.min(gradientSteps - 1, Math.floor((normalizedValue * 100) / step));
        const ratio = stepIndex / (gradientSteps - 1);
        
        return ColorUtils.getColorInGradient(lowColorRgb, highColorRgb, ratio);
    };

    // 生成网格样式
    const gridStyle = useMemo<React.CSSProperties>(() => ({
        '--grid-cols': heatmapConfig.cols.toString(),
        '--grid-gap': `${heatmapConfig.gap}${heatmapConfig.gapUnit}`
    }), [heatmapConfig.cols, heatmapConfig.gap, heatmapConfig.gapUnit]);

    // 渲染单元格
    const renderCells = useMemo(() => {
        return heatmapConfig.data.flatMap((rowData, rowIndex) => 
            rowData.map((cellValue, colIndex) => {
                // 移除百分比计算，仅保留值显示
                
                return (
                    <div
              key={`cell-${rowIndex}-${colIndex}`}
              className="square-cell" tabIndex={0}
              style={{
                  borderRadius: `${heatmapConfig.rounded}${heatmapConfig.roundedUnit}`,
                  backgroundColor: getCellColor(cellValue)
              }}
              onClick={() => onCellClick && onCellClick(rowIndex, colIndex, cellValue)}
              data-row={rowIndex}
              data-col={colIndex}
              data-value={cellValue}
              
          ></div>
                );
            })
        );
    }, [heatmapConfig, onCellClick]);

    return (
        <div className="heatmap-container-wrapper bg-gray-100 rounded-lg h-full">
            <div 
                id={id} 
                className="heatmap-grid w-full h-full"
                style={gridStyle}
            >
                {renderCells}
            </div>
        </div>
    );
};

export default Heatmap;